package com.ophiux.common.data.tenant;

import com.ophiux.common.data.constants.CommonConstants;
import com.ophiux.common.data.headers.HeaderParamsContextHolder;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

/**
 * @desc: feign请求头中添加参数
 * @author: hhl
 * @date：2022/9/6 13:21
 */
@Slf4j
public class OphiuxFeignTenantInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        if (TenantContextHolder.getTenantId() == null) {
            log.debug("TTL 中的 租户ID为空，feign拦截器 >> 跳过");
            return;
        }

        String tenantId = TenantContextHolder.getTenantId().toString();
        String userClientType = "";
        if (!ObjectUtils.isEmpty(HeaderParamsContextHolder.getHeaderParams())) {
            if (!ObjectUtils.isEmpty(HeaderParamsContextHolder.getHeaderParams().getAccessToken())) {
                requestTemplate.header(CommonConstants.TOKEN, HeaderParamsContextHolder.getHeaderParams().getAccessToken() + "");
            }
            if (!ObjectUtils.isEmpty(HeaderParamsContextHolder.getHeaderParams().getUserClientType())) {
                requestTemplate.header(CommonConstants.USER_CLIENT_TYPE, HeaderParamsContextHolder.getHeaderParams().getUserClientType() + "");
                userClientType = HeaderParamsContextHolder.getHeaderParams().getUserClientType();
            }
        }
        log.info("Feign headers传递：当前租户id={}，userType={}", tenantId, userClientType);
        requestTemplate.header(CommonConstants.TENANT_ID, tenantId);
    }

}
